import sys
import os

# 动态添加项目根目录到 Python 路径
current_dir = os.path.dirname(os.path.abspath(__file__))
project_root = os.path.dirname(current_dir)
sys.path.append(project_root)

from src.agents.retrieval_agent import RetrievalAgent
from src.agents.summarization_agent import SummarizationAgent
from src.agents.comparison_agent import ComparisonAgent
from src.agents.structuring_agent import StructuringAgent
from src.utils.citation_manager import CitationManager

def generate_review(query, review_type='status', references=None):
    """
    生成文献综述
    :param query: 查询文本
    :param review_type: 综述类型 ('concept', 'status', 'comparison', 'timeline')
    :param references: 参考文献列表
    :return: 返回生成的文献综述和引文索引
    """
    # 初始化智能体
    retrieval_agent = RetrievalAgent()
    summarization_agent = SummarizationAgent()
    comparison_agent = ComparisonAgent()
    structuring_agent = StructuringAgent()
    citation_manager = CitationManager()
    
    # 1. 检索相关论文
    papers = retrieval_agent.retrieve_papers(query)
    
    # 2. 生成论文摘要
    summaries = summarization_agent.generate_summaries(papers)
    
    # 3. 根据综述类型进行处理
    if review_type == 'comparison':
        # 对于比较类型的综述，使用比较智能体进行方法对比
        content = comparison_agent.compare_methods(summaries)
    else:
        # 对于其他类型的综述，直接使用摘要
        content = summaries
    
    # 4. 结构化处理并添加引用
    review = structuring_agent.structure_review(content, review_type)
    review = citation_manager.add_citations(review, papers)
    
    # 5. 生成参考文献列表
    references = citation_manager.generate_references()
    
    return {
        'content': review,
        'references': references
    }

def generate_reference_list(references):
    """
    生成参考文献列表
    :param references: 参考文献列表，包含引用的文献信息
    :return: 格式化后的参考文献列表
    """
    from src.utils.citation_formatter import CitationFormatter
    
    formatter = CitationFormatter()
    return formatter.format_references(references)

### 2. 文献管理
def generate_reference_list(references):
    """
    生成参考文献列表
    :param references: 参考文献列表，包含引用的文献信息
    :return: 格式化后的参考文献列表
    """
    from src.utils.citation_formatter import CitationFormatter
    
    formatter = CitationFormatter()
    reference_list = "## Reference\n\n"
    
    # 按编号排序确保顺序一致
    sorted_refs = sorted(references, key=lambda x: x['number'])
    
    for ref in sorted_refs:
        # 使用APA格式化引用
        formatted_ref = formatter.format_apa_reference(ref)
        reference_list += formatted_ref + "\n"
        
    return reference_list

def generate_review_from_args(query, review_type='status', references=None):
    return generate_review(query, review_type, references)

if __name__ == "__main__":
    # 示例1：技术概念综述
    concept_query = "Loss function"
    concept_review = generate_review_from_args(concept_query, review_type='concept')
    print("Concept review:\n", concept_review)

    # 示例2：研究现状综述
    status_query = "What is the current research status of Text2SQL and what challenges does it face?"
    status_review = generate_review_from_args(status_query, review_type='status')
    print("Status review:\n", status_review)

    # 新增题目及查询
    tenrec_query = "The instance numbers of different types of datasets (QK videos, QB videos, QK articles, QB articles) in the Tenrec dataset vary greatly. What impact will this difference have on the training and evaluation of recommender systems?"
    tenrec_review = generate_review_from_args(tenrec_query, review_type='status')
    print("Tenrec-related review:\n", tenrec_review)

    weber_query = "When the qPWAWS algorithm handles singular points, compared with the previous Weiszfeld algorithm, in which aspects does its superlinear convergence property show advantages in experiments with real financial datasets?"
    weber_review = generate_review_from_args(weber_query, review_type='status')
    print("Weber-related review:\n", weber_review)

    driving_query = "In the deep reinforcement learning algorithm based on implicit imitation, how can we ensure that the observer agent can effectively adapt and possibly surpass the behavior of the tutor in non-visited states?"
    driving_review = generate_review_from_args(driving_query, review_type='status')
    print("Autonomous driving-related review:\n", driving_review)

    eqnet_query = "How does the elastic quantization space design proposed by EQ-Net solve the problem of inconsistent requirements for model quantization forms on different hardware platforms?"
    eqnet_review = generate_review_from_args(eqnet_query, review_type='status')
    print("EQ-Net-related review:\n", eqnet_review)